{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn import preprocessing\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.model_selection import train_test_split\n",
    "%matplotlib inline\n",
    "knn = KNeighborsClassifier()\n",
    "plt.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体\n",
    "plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "F:\\01sofeware\\python-Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:2: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n",
      "  \n",
      "F:\\01sofeware\\python-Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:3: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n",
      "  This is separate from the ipykernel package so we can avoid doing imports until\n",
      "F:\\01sofeware\\python-Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:4: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n",
      "  after removing the cwd from sys.path.\n"
     ]
    }
   ],
   "source": [
    "data = pd.read_table('../data/datingTestSet.txt',names=['mileage','game_percentage','ice','like_degree'])\n",
    "data.like_degree[data.like_degree=='largeDoses']=0  \n",
    "data.like_degree[data.like_degree=='smallDoses']=1\n",
    "data.like_degree[data.like_degree=='didntLike']=2\n",
    "data = np.array(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from my_sklearn.my_knn import My_knn\n",
    "data1=data[:,0:3] \n",
    "data_test = np.apply_along_axis(My_knn.mean_std,0,data1) #均值归一化样本\n",
    "data_score = data[:,-1] #结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "num=int(len(data_test))\n",
    "a=int(num*0.8)\n",
    "# 按百分比80训练\n",
    "x_train=data_test[0:a] #训练集\n",
    "y_train=data_score[0:a]\n",
    "x_test=data_test[0:(num-a)] # 测试集\n",
    "y_test=data_score[0:(num-a)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.965"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn.fit(x_train,y_train.astype('int'))\n",
    "# 测试评分为0.965,模型训练通过\n",
    "knn.score(x_test,y_test.astype('int'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
       "           metric_params=None, n_jobs=1, n_neighbors=5, p=2,\n",
       "           weights='uniform')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a=knn.fit(x_train,y_train.astype('int'))\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最佳的k值 3\n",
      "最佳的评分 0.985\n"
     ]
    }
   ],
   "source": [
    "best_k=-1\n",
    "best_score=0\n",
    "for k in range(2,11):\n",
    "    all=KNeighborsClassifier(n_neighbors=k)\n",
    "    all.fit(x_train,y_train.astype('int'))\n",
    "    score_k=all.score(x_test,y_test.astype('int'))\n",
    "    if score_k > best_score:\n",
    "        best_score=score_k\n",
    "        best_k=k\n",
    "print('最佳的k值',best_k)\n",
    "print('最佳的评分',best_score)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import GridSearchCV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "param_grid = [{\n",
    "    'weights':['uniform'],\n",
    "    'n_neighbors':[i for i in range(1,11)]\n",
    "},\n",
    "{\n",
    "    'weights':['distance'],\n",
    "    'n_neighbors':[i for i in range(1,11)],\n",
    "    'p':[i for i in range(1,11)]\n",
    "}]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "gr = GridSearchCV(knn,param_grid=param_grid)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "data_test,data_score\n",
    "X = data_test\n",
    "y = data_score\n",
    "X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)\n",
    "print(type(X_train))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 3.64 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "GridSearchCV(cv=None, error_score='raise',\n",
       "       estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
       "           metric_params=None, n_jobs=1, n_neighbors=5, p=2,\n",
       "           weights='uniform'),\n",
       "       fit_params=None, iid=True, n_jobs=1,\n",
       "       param_grid=[{'weights': ['uniform'], 'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}, {'weights': ['distance'], 'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'p': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}],\n",
       "       pre_dispatch='2*n_jobs', refit=True, return_train_score='warn',\n",
       "       scoring=None, verbose=0)"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "gr.fit(X_train,y_train.astype('int'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'n_neighbors': 5, 'p': 4, 'weights': 'distance'}"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.best_params_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.965"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
       "           metric_params=None, n_jobs=1, n_neighbors=5, p=4,\n",
       "           weights='distance')"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.best_estimator_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.95"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gr.best_estimator_.score(X_test,y_test.astype('int'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.rchCV(knn,param_grid=param_grid)\n",
    "array([30000,10,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 0, 2, 2, 0, 2, 0, 0, 0, 0]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arry=[]\n",
    "for i in data1:\n",
    "    arry.append(np.sqrt(np.sum((x-i)**2)))\n",
    "# 获取每个点之间的距离,进行排序\n",
    "data_sort=np.argsort(arry)\n",
    "# 获取最前面6个点的结果\n",
    "score_min=[data_score[i] for i in data_sort[:10]]\n",
    "score_min\n",
    "#返回结果为极具魅力的人"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "    1) 不喜欢的人  didntLike 2\n",
    "    2) 魅力一般的人 smallDoses 1\n",
    "    3) 极具魅力的人  largeDoses 0"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
